package com.fly.core.ds;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ExecutionException;

import javax.sql.DataSource;

import com.fly.common.utils.SpringContextUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * Spring数据源(jdbc-pool)管理工具
 * 
 * @author 00fly
 * @version [版本号, 2018-09-26]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
public class SpringPool extends BaseDataSource
{
    private static DataSource dataSource;
    
    /**
     * <默认构造函数>
     */
    private SpringPool()
    {
        super();
    }
    
    private static final SpringPool SINGLE = new SpringPool();
    
    /**
     * 单例获取对象
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static SpringPool getInstance()
    {
        return SINGLE;
    }
    
    /**
     * 获取数据库连接
     * 
     * @return
     * @throws SQLException
     * @throws ExecutionException
     * @throws InterruptedException
     * @see [类、类#方法、类#成员]
     */
    @Override
    public Connection getConnection()
        throws SQLException
    {
        try
        {
            Connection connection = threadLocal.get();
            if (connection == null)
            {
                // 获取spring管理的数据源
                dataSource = SpringContextUtils.getBean(DataSource.class);
                connection = dataSource.getConnection();
                threadLocal.set(connection); // 把 connection绑定到当前线程上
            }
            log.info("★★★★申请资源: {}", connection);
            return connection;
        }
        catch (Exception e)
        {
            throw new SQLException(e.getMessage(), e.getCause());
        }
    }
}